<template>
  <div class="setting-container">
    <!-- 用户信息区域 -->
    <el-card class="user-info-card" shadow="hover">
      <div slot="header" class="card-header">
        <span>用户信息</span>
      </div>
      <div class="user-info">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="label">用户ID:</span>
              <span class="value">{{ userInfo.userId || '未登录' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="label">用户名:</span>
              <span class="value">{{ userInfo.username || '未登录' }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row style="margin-top: 20px;">
          <el-col :span="24">
            <el-button type="danger" @click="handleLogout" :loading="logoutLoading">
              退出登录
            </el-button>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 第三方品牌绑定区域 -->
    <el-card class="brands-card" shadow="hover">
      <div slot="header" class="card-header">
        <span>第三方品牌绑定管理</span>
        <el-button type="primary" size="small" @click="refreshBindings" :loading="refreshLoading">
          刷新状态
        </el-button>
      </div>

      <div class="brands-list">
        <div v-for="brand in supportedBrands" :key="brand.name" class="brand-item">
          <div class="brand-info">
            <div class="brand-logo" :style="{ backgroundColor: brand.color }">
              {{ brand.displayName.charAt(0) }}
            </div>
            <div class="brand-details">
              <h3 class="brand-name">{{ brand.displayName }}</h3>
              <p class="brand-status" :class="{
                'bound': brand.isBound && !brand.isExpired,
                'expired': brand.isExpired,
                'unbound': !brand.isBound
              }">
                {{ getBrandStatus(brand) }}
              </p>
            </div>
          </div>

          <div class="brand-actions">
            <el-button
              v-if="!brand.isBound || brand.isExpired"
              type="primary"
              size="small"
              @click="handleBind(brand.name)"
              :loading="brand.loading"
            >
              {{ brand.isExpired ? '重新绑定' : '绑定账号' }}
            </el-button>

            <el-button
              v-if="brand.isBound && !brand.isExpired"
              type="danger"
              size="small"
              @click="handleUnbind(brand.name)"
              :loading="brand.loading"
            >
              解绑账号
            </el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 绑定授权码对话框 -->
    <el-dialog
      title="绑定第三方账号"
      v-model="bindDialogVisible"
      width="400px"
      @close="resetBindDialog"
    >
      <div class="bind-dialog-content">
        <p>请输入{{ currentBrandName }}的授权码：</p>
        <el-input
          v-model="authCode"
          placeholder="请输入授权码"
          clearable
        />
        <div class="dialog-tip">
          <p>如何获取授权码？</p>
          <ol>
            <li>访问{{ currentBrandName }}官方授权页面</li>
            <li>使用您的{{ currentBrandName }}账号登录</li>
            <li>同意授权并获取授权码</li>
            <li>将授权码输入到上方输入框</li>
          </ol>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="bindDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmBind" :loading="bindLoading">
            确认绑定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Setting',
  data() {
    return {
      userInfo: {
        userId: '',
        username: ''
      },
      logoutLoading: false,
      refreshLoading: false,
      bindDialogVisible: false,
      bindLoading: false,
      currentBrandName: '',
      authCode: '',

      // 支持的品牌列表
      supportedBrands: [
        {
          name: 'xiaomi',
          displayName: '小米',
          color: '#ff6900',
          isBound: false,
          isExpired: false,
          loading: false
        },
        {
          name: 'midea',
          displayName: '美的',
          color: '#0066cc',
          isBound: false,
          isExpired: false,
          loading: false
        }
      ]
    }
  },

  mounted() {
    this.loadUserInfo()
    this.loadBindings()
  },

  methods: {
    // 加载用户信息
    loadUserInfo() {
      // 这里可以通过API获取当前登录用户信息
      // 暂时使用本地存储的信息
      const userData = localStorage.getItem('flow_system_user')
      if (userData) {
        try {
          this.userInfo = JSON.parse(userData)
        } catch (error) {
          console.error('解析用户信息错误:', error)
        }
      }
    },

    // 加载绑定状态
    async loadBindings() {
      try {
        this.refreshLoading = true
        const result = await window.api.getBindings()

        if (result && result.success && result.bindings) {
          // 更新绑定状态
          this.supportedBrands.forEach(brand => {
            const bindingInfo = result.bindings[brand.name]
            if (bindingInfo) {
              brand.isBound = bindingInfo.isBound
              brand.isExpired = bindingInfo.isExpired
            }
          })
        }
      } catch (error) {
        console.error('加载绑定状态错误:', error)
        this.$message.error('加载绑定状态失败')
      } finally {
        this.refreshLoading = false
      }
    },

    // 刷新绑定状态
    async refreshBindings() {
      await this.loadBindings()
      this.$message.success('绑定状态已刷新')
    },

    // 获取品牌状态文本
    getBrandStatus(brand) {
      if (!brand.isBound) {
        return '未绑定'
      } else if (brand.isExpired) {
        return '已过期'
      } else {
        return '已绑定'
      }
    },

    // 处理绑定
    handleBind(brandName) {
      this.currentBrandName = this.supportedBrands.find(b => b.name === brandName)?.displayName || brandName
      this.bindDialogVisible = true
    },

    // 确认绑定
    async confirmBind() {
      if (!this.authCode.trim()) {
        this.$message.warning('请输入授权码')
        return
      }

      try {
        this.bindLoading = true
        const brandName = this.supportedBrands.find(b => b.displayName === this.currentBrandName)?.name

        const result = await window.api.bindThirdParty(brandName, this.authCode)

        if (result && result.success) {
          this.$message.success('绑定成功！')
          this.bindDialogVisible = false
          this.resetBindDialog()
          await this.loadBindings()
        } else {
          this.$message.error(result.message || '绑定失败')
        }
      } catch (error) {
        console.error('绑定错误:', error)
        this.$message.error('绑定请求失败')
      } finally {
        this.bindLoading = false
      }
    },

    // 处理解绑
    async handleUnbind(brandName) {
      const brand = this.supportedBrands.find(b => b.name === brandName)

      try {
        await this.$confirm(`确认解绑${brand.displayName}账号吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        brand.loading = true
        const result = await window.api.unbindThirdParty(brandName)

        if (result && result.success) {
          this.$message.success('解绑成功！')
          await this.loadBindings()
        } else {
          this.$message.error(result.message || '解绑失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('解绑错误:', error)
          this.$message.error('解绑请求失败')
        }
      } finally {
        brand.loading = false
      }
    },

    // 重置绑定对话框
    resetBindDialog() {
      this.authCode = ''
      this.currentBrandName = ''
      this.bindLoading = false
    },

    // 处理登出
    async handleLogout() {
      try {
        await this.$confirm('确认退出登录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        this.logoutLoading = true
        const result = await window.api.logout()

        if (result && result.success) {
          this.$message.success('已退出登录')
          // 跳转到登录页面
          this.$router.push('/login')
        } else {
          this.$message.error('登出失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('登出错误:', error)
          this.$message.error('登出请求失败')
        }
      } finally {
        this.logoutLoading = false
      }
    }
  }
}
</script>

<style scoped>
.setting-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.user-info-card,
.brands-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}

.user-info {
  padding: 10px 0;
}

.info-item {
  margin-bottom: 10px;
}

.info-item .label {
  color: #909399;
  margin-right: 10px;
}

.info-item .value {
  color: #303133;
  font-weight: 500;
}

.brands-list {
  padding: 10px 0;
}

.brand-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  margin-bottom: 15px;
  transition: all 0.3s ease;
}

.brand-item:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.brand-info {
  display: flex;
  align-items: center;
}

.brand-logo {
  width: 50px;
  height: 50px;
  margin-right: 15px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
  font-weight: bold;
}

.brand-details h3 {
  margin: 0 0 5px 0;
  color: #303133;
  font-size: 16px;
}

.brand-status {
  margin: 0;
  font-size: 14px;
  padding: 2px 8px;
  border-radius: 4px;
  display: inline-block;
}

.brand-status.bound {
  background-color: #f0f9ff;
  color: #1890ff;
}

.brand-status.expired {
  background-color: #fff2e8;
  color: #fa8c16;
}

.brand-status.unbound {
  background-color: #f5f5f5;
  color: #8c8c8c;
}

.brand-actions {
  display: flex;
  gap: 10px;
}

.bind-dialog-content {
  padding: 10px 0;
}

.dialog-tip {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid #1890ff;
}

.dialog-tip p {
  margin: 0 0 10px 0;
  font-weight: 500;
  color: #303133;
}

.dialog-tip ol {
  margin: 0;
  padding-left: 20px;
  color: #666;
}

.dialog-tip li {
  margin-bottom: 5px;
  line-height: 1.5;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .brand-item {
    flex-direction: column;
    text-align: center;
  }

  .brand-info {
    margin-bottom: 15px;
  }

  .brand-actions {
    width: 100%;
    justify-content: center;
  }
}
</style>
